<template>
  <div class="app-container">
    <div>
      <div class="auth-header-container">
        <div class="auth-header">
          <h1>授权 {{ application.displayName }}</h1>
        </div>

        <div class="auth-client-info">
          <div class="client-byline">
             <div
                  class="client-logo placeholder-logo"
              >
                   {{ firstLetter }}
            </div>
            <span>------------</span
            ><svg class="scope-icon" viewBox="0 0 16 16" width="16" height="16">
              <path
                fill="#2da44e"
                d="M8 16A8 8 0 1 1 8 0a8 8 0 0 1 0 16zm3.78-9.72a.751.751 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018L6.75 9.19 5.28 7.72a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.09-.02l4.5-5z"
              /></svg
            ><span>------------</span>
            <el-image :src="openIddictImg" alt="域名Logo" class="domain-logo" />
          </div>
          <div class="client-description">
            此应用将能够访问您的OpenIddict账户
          </div>
        </div>
      </div>
      <div class="auth-container">
        <div class="auth-permissions">
          <h3>公开权限</h3>
          <p class="permission-description">此应用将获取以下权限：</p>
          <div class="scope-list">
            <div
              class="scope-item"
              v-for="scope in filteredPermissions"
              :key="scope"
            >
              <svg
                class="scope-icon"
                viewBox="0 0 16 16"
                width="16"
                height="16"
              >
                <path
                  fill="#2da44e"
                  d="M8 16A8 8 0 1 1 8 0a8 8 0 0 1 0 16zm3.78-9.72a.751.751 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018L6.75 9.19 5.28 7.72a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.09-.02l4.5-5z"
                />
              </svg>
              <span>{{ scopeDescription(scope) }}</span>
            </div>
            <div class="scope-item">
              <svg
                class="scope-icon"
                viewBox="0 0 16 16"
                width="16"
                height="16"
              >
                <path
                  fill="#2da44e"
                  d="M8 16A8 8 0 1 1 8 0a8 8 0 0 1 0 16zm3.78-9.72a.751.751 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018L6.75 9.19 5.28 7.72a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.09-.02l4.5-5z"
                />
              </svg>
              <span>识别您的身份</span>
            </div>
            <div class="scope-item">
              <svg
                class="scope-icon"
                viewBox="0 0 16 16"
                width="16"
                height="16"
              >
                <path
                  fill="#2da44e"
                  d="M8 16A8 8 0 1 1 8 0a8 8 0 0 1 0 16zm3.78-9.72a.751.751 0 0 0-.018-1.042.75.75 0 0 0-1.042-.018L6.75 9.19 5.28 7.72a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.09-.02l4.5-5z"
                />
              </svg>
              <span>获取您的公开信息</span>
            </div>
          </div>
        </div>

        <div class="auth-divider"></div>

        <div class="auth-actions">
          <button class="auth-cancel" @click="cancelAuth">取消</button>
          <button class="auth-confirm" @click="submitForm">
            授权 {{ application.displayName }}
          </button>
        </div>

        <div class="auth-redirect-notice">
          授权请求重定向至 {{ data.redirect_uri }}
        </div>

        <div class="auth-divider"></div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="Auth">
import { ElMessageBox } from "element-plus";
import { onMounted, ref, computed } from "vue";
import { useRoute } from "vue-router";
import openIddictImg from "@/assets/openid.png";
import {
  FindClientByClientId,
  OpenIddictApplicationDto,
} from "@/api/application";
const router = useRoute();
const data = ref<Record<string, string>>({});

const siteName = "Ginko";
const currentYear = new Date().getFullYear();

onMounted(async () => {
  await getClientInfo();
  data.value = router.query as Record<string, string>;
});

const firstLetter = computed(() => {
  if (!application.value.displayName) return '';

  // 取第一个字符
  return application.value.displayName.trim().charAt(0).toUpperCase();
});

const parsedScopes = computed(() => {
  return data.value.scope?.split(" ") || [];
});

const scopeDescription = (scope: string) => {
  const descriptions: Record<string, string> = {
    "scp:profile": "获取您的个人资料",
    "scp:email": "获取您的邮箱地址",
    "scp:phone": "获取您的电话号码",
    "scp:address": "获取您的地址",
  };
  return descriptions[scope] || null;
};

const cancelAuth = () => {
  ElMessageBox.confirm("您确定要取消授权吗？取消后需要重新登录", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      localStorage.removeItem("state");
      localStorage.removeItem("code_verifier");
      let redirectUrl = `${
        import.meta.env.VITE_API_BASE_URL
      }/connect/authorize/confirm?accept=false`;
      for (const key in data.value) {
        if (data.value.hasOwnProperty(key)) {
          redirectUrl += `&${encodeURIComponent(key)}=${encodeURIComponent(
            data.value[key]
          )}`;
        }
      }
      window.location.href = redirectUrl;
    })
    .catch(() => {
      // 用户点击了取消按钮，不执行任何操作
    });
};

const filteredPermissions = computed(() => {
  return permissions.value.filter((scope) => scopeDescription(scope));
});

const submitForm = () => {
  let redirectUrl = `${
    import.meta.env.VITE_API_BASE_URL
  }/connect/authorize/confirm?accept=true`;
  for (const key in data.value) {
    if (data.value.hasOwnProperty(key)) {
      redirectUrl += `&${encodeURIComponent(key)}=${encodeURIComponent(
        data.value[key]
      )}`;
    }
  }
  window.location.href = redirectUrl;
};

const application = ref(new OpenIddictApplicationDto());
const permissions = ref([]);
const getClientInfo = async () => {
  const clientId = router.query["client_id"];
  application.value = await FindClientByClientId(clientId);
  permissions.value = JSON.parse(application.value.permissions);
};
</script>

<style lang="scss" scoped>
.app-container {
  align-items: center;
  display: flex;
  justify-content: center;
  width: 100vw;
  background-color: #f6f8fa;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial,
    sans-serif;
  color: #24292f;
}

.auth-header-container {
  width: 548px;

  margin-bottom: 20px;
  text-align: center;
}

.auth-client-info {
  .client-byline {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 14px;
    color: #57606a;
    margin-bottom: 4px;

    .client-logo,
    .domain-logo {
      height: 50px;
      border-radius: 50%; /* 使图片变为圆形 */
      width: 50px;
      max-width: 120px;
      object-fit: cover;
    }

    span {
      margin: 0 4px;
    }
  }

  .client-description {
    font-size: 16px;
    font-weight: 400;
    margin-top: 20px;
  }
}

.auth-container {
  width: 500px;

  background-color: #ffffff;
  border: 1px solid #d8dee4;
  border-radius: 6px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
}

.auth-header {
  margin-bottom: 20px;
  text-align: center;

  h1 {
    font-size: 34px;
    font-weight: bold;
    margin: 0;
  }
}

.auth-client-info {
  text-align: center;
  margin-bottom: 20px;

  .client-byline {
    font-size: 14px;
    color: #57606a;
    margin-bottom: 4px;
  }

  .client-description {
    font-size: 16px;
    font-weight: 400;
  }
}

.auth-permissions {
  background-color: #f6f8fa;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 20px;

  h3 {
    font-size: 16px;
    font-weight: 600;
    margin: 0 0 8px 0;
  }

  .permission-description {
    font-size: 14px;
    color: #57606a;
    margin: 0 0 12px 0;
    text-align: left;
  }
}

.scope-list {
  margin: 16px 0;
}

.scope-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;

  .scope-icon {
    margin-right: 8px;
    flex-shrink: 0;
  }
}

.auth-divider {
  height: 1px;
  background-color: #d8dee4;
  margin: 24px 0;
}

.auth-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;

  button {
    flex: 1;
    padding: 8px 16px;
    font-size: 14px;
    font-weight: 500;
    border-radius: 6px;
    cursor: pointer;
    border: 1px solid;
  }

  .auth-cancel {
    background-color: #ffffff;
    border-color: rgba(27, 31, 36, 0.15);
    color: #24292f;

    &:hover {
      background-color: #f6f8fa;
      border-color: rgba(27, 31, 36, 0.15);
    }
  }

  .auth-confirm {
    background-color: #2da44e;
    border-color: rgba(27, 31, 36, 0.15);
    color: #ffffff;

    &:hover {
      background-color: #2c974b;
    }
  }
}

.auth-redirect-notice {
  font-size: 12px;
  color: #57606a;
  text-align: center;
  margin-bottom: 16px;
}

.auth-footer {
  font-size: 12px;
  color: #57606a;
  text-align: center;

  .footer-meta {
    display: flex;
    flex-direction: column;
    gap: 4px;
    margin-bottom: 12px;

    .meta-item {
      color: #57606a;
    }
  }

  .footer-links {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 8px 12px;
    margin-bottom: 8px;

    a {
      color: #0969da;
      text-decoration: none;
      white-space: nowrap;

      &:hover {
        text-decoration: underline;
      }
    }
  }

  .footer-notice {
    margin-bottom: 8px;
    font-size: 11px;
    color: #6e7781;
  }

  .copyright {
    margin-top: 8px;
  }
}

.client-byline {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
  color: #57606a;
  margin-bottom: 4px;

  .client-logo,
  .domain-logo {
    height: 20px;
    width: auto;
    max-width: 120px;
    object-fit: contain;
  }

  span {
    margin: 0 4px;
  }
}

@media (max-width: 600px) {
  .auth-header-container,
  .auth-container {
    width: 100vw !important;
    min-width: 0 !important;
    max-width: 100vw !important;
    border-radius: 0;
    padding: 12px !important;
    box-sizing: border-box;
  }
  .app-container {
    padding: 0 !important;
  }
}

.placeholder-logo {
  height: 50px;
  width: 50px;
  border-radius: 50%;
  background-color: #409eff; /* 可以换成你喜欢的颜色 */
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: bold;
}
</style>